import requests
import json
import redis
import logging
from .settings import REDIS_URL,DEFAULT_REQUEST_HEADERS

logger = logging.getLogger(__name__)
##使用REDIS_URL链接Redis数据库, deconde_responses=True这个参数必须要，数据会变成byte形式 完全没法用
reds = redis.Redis.from_url(REDIS_URL, db=6, decode_responses=True)
login_url = 'https://passport.csdn.net/v1/register/pc/login/doLogin'

#cookie转化格式
class transCookie:
    def __init__(self, cookie):
        self.cookie = cookie

    def stringToDict(self):
        '''
        将从浏览器上Copy来的cookie字符串转化为Dict
        :return:
        '''
        itemDict = {}
        items = self.cookie.split(';')
        for item in items:
            key = item.split('=')[0].replace(' ', '')
            value = item.split('=')[1]
            itemDict[key] = value
        return itemDict
    def dictToString(self,cookies_dict):
        '''
        还原Dict 为字符串形式
        :return:
        '''
        return ';'.join(['{}={}'.format(k,v) for k,v in cookies_dict])


##获取Cookie
def get_cookie(account,password):
    s = requests.Session()
    payload = {
        'loginType': "1",
        'pwdOrVerifyCode': password,
        'uaToken': "137#r9E9hE9oUEDeOWYEAcn5T9ODIn9bif3d/7n6Dfnpyv4z2nr0IL+KWEE9J7Ouwzh1u5p6ShCCldQ5mmB2qBHUFQA7F1e4fCOzdvly5Db3VMCh87m8L3bJNU4ZKyRtX1VbEX+haJYTV0Xaj9iH/JkX76BSXLIuef+CKry1VBsSbbKlqzckkBotsODJ7+kY4AyeM7bCql+IkyV3Wchd4dEaTDopLfNmrhKxif/mPvz6VvQZ5/IPK4BI+hO4cLiG6R+n6trgkYEiM6Yn86W9Oh7u8c1+tLiXymGpDPFjPTAWlWGhVdJIfMny971Eo7Ia5+YLkAqJd1HFqMdaFoIKJ3V9mLLHrfVmXA1sTq4fYHXUiDyO76xjNTm0n2wJ6QEtU9LvroelFjH84+q951dZP8Hf0VINvGZipJahpBkFmJrBTjcZumoogCLL6wpoaMN9VmfBRaqSgEFzII5oe4Q7U+V6UY0yd+zGrvVcPc3EfM4GVQxFjIu/GTkFn7nhDWS/pQWIUbfKQH3EclxZ428A+d7DomOFAAz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O2gNj9frVdm5WTKktb1A/TEiyHnZk/NB4fvDQqqNyUBU9X+pWesoW9GAPKA8U8L7GUhz3T4Erd9kpZva9R8KCZwP3gQMsvwo=",
        'userIdentification': account,
        'webUmidToken': "T2gATphHx97IABX-2a3Kr6bAP2veDP8-_oWhw3QtLpK-muFQ_wQLjiVBssUe8UFv7RQN7jdGUZQfLJtoho74PBwC"
    }
    response = s.post(login_url, data=payload)
    cookies = response.cookies.get_dict()
    trans=transCookie(DEFAULT_REQUEST_HEADERS['Cookie'])
    headers_cookie=trans.stringToDict()
    headers_cookie.update(cookies)
    DEFAULT_REQUEST_HEADERS['Cookie']=trans.dictToString(headers_cookie)
    logger.warning("获取Cookie成功！（账号为:%s）"%account)
    return json.dumps(cookies)

def init_cookie(red, spidername):
    redkeys = reds.keys()
    for user in redkeys:
        password = reds.get(user)
        if red.get("%s:Cookies:%s--%s" % (spidername, user, password)) is None:
            cookie = get_cookie(user, password)
            red.set("%s:Cookies:%s--%s"% (spidername, user, password), cookie)